<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        html,
        body {
            height: 100%;
        }

        body {
            background: #f5f6fa;
            color: #222;
            min-height: 100vh;
            height: 100vh;
            padding: 20px;
        }

        .container {
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            height: calc(100vh - 40px);
            /* 40px为body上下padding */
        }

        .param-bar,
        .chart-tabs,
        header,
        footer {
            flex-shrink: 0;
        }

        .main-flex {
            display: flex;
            flex-direction: row;
            gap: 20px;
            width: 100%;
            height: calc(100vh - 180px);
        }

        .chart-section {
            width: 68%;
            display: flex;
            flex-direction: column;
            height: 100%;
            align-items: flex-start;
        }

        .list-section {
            width: 38%;
            display: flex;
            flex-direction: column;
            height: 100%;
            align-items: flex-end;
        }

        .tab-content {
            flex: 1;
            width: 100%;
            display: block;
            min-height: 0;
            background: #fff;
            border-radius: 0 0 8px 8px;
            margin-top: 0;
            padding-top: 0;
        }

        .chart-container {
            width: 100%;
            flex: 1 1 0;
            min-height: 600px;
            max-height: 80vh;
            background: #fff;
            border-radius: 10px;
            position: relative;
        }

        .chart-title {
            color: #ff6600;
            margin-bottom: 12px;
            font-size: 1.25rem;
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: bold;
        }

        .chart {
            height: 400px;
            width: 100%;
        }

        .formula-section {
            background: rgba(16, 42, 67, 0.85);
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4);
            border: 1px solid rgba(64, 224, 208, 0.15);
            margin-top: 25px;
        }

        .formula-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }

        .formula-card {
            background: rgba(0, 20, 40, 0.6);
            border-radius: 10px;
            padding: 20px;
            border-left: 4px solid #40e0d0;
        }

        .formula-title {
            color: #20b2aa;
            margin-bottom: 15px;
            font-size: 1.2rem;
        }

        .formula {
            font-family: 'Courier New', monospace;
            font-size: 1.3rem;
            color: #ffcc66;
            margin: 15px 0;
            padding: 15px;
            background: rgba(0, 0, 0, 0.3);
            border-radius: 8px;
            text-align: center;
        }

        .explanation {
            color: #c0e8f0;
            line-height: 1.6;
        }

        .event-marker {
            position: absolute;
            top: 10px;
            right: 20px;
            background: rgba(255, 77, 77, 0.2);
            padding: 8px 15px;
            border-radius: 20px;
            border: 1px solid rgba(255, 77, 77, 0.5);
            font-size: 0.9rem;
            color: #ff9999;
        }

        footer {
            text-align: center;
            padding: 30px 0;
            margin-top: 40px;
            color: #7fdbda;
            font-size: 0.95rem;
            border-top: 1px solid rgba(64, 224, 208, 0.2);
        }

        .legend {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            gap: 15px;
            margin-top: 20px;
        }

        .legend-item {
            display: flex;
            align-items: center;
            font-size: 0.9rem;
        }

        .legend-color {
            width: 20px;
            height: 20px;
            margin-right: 8px;
            border-radius: 4px;
        }

        .export-btn {
            position: absolute;
            top: 10px;
            right: 18px;
            z-index: 10;
            background: linear-gradient(90deg, #ff6600, #ff944d);
            border: none;
            border-radius: 6px;
            color: #fff;
            font-size: 1em;
            font-weight: bold;
            padding: 6px 16px;
            cursor: pointer;
            box-shadow: 0 2px 8px rgba(255, 102, 0, 0.08);
            transition: background 0.2s, box-shadow 0.2s;
        }

        .export-btn:hover {
            background: linear-gradient(90deg, #ff944d, #ff6600);
            box-shadow: 0 4px 16px rgba(255, 102, 0, 0.18);
        }

        .chart-tabs {
            display: flex;
            margin-bottom: 0;
            background: #fff;
            border-radius: 8px 8px 0 0;
            box-shadow: none;
            border-bottom: 1px solid #e0e0e0;
        }

        .tab-btn {
            color: #333;
            background: #fff;
            border: none;
            padding: 10px 32px;
            font-size: 1.1em;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            position: relative;
            transition: color 0.2s, border 0.2s;
            box-shadow: none;
        }

        .tab-btn.active {
            background: #fff;
            color: #ff6600;
            box-shadow: none;
        }

        .tab-btn.active::after {
            content: '';
            position: absolute;
            left: 20%;
            right: 20%;
            bottom: 0;
            height: 3px;
            background: #ff6600;
            border-radius: 2px;
        }

        .power-table-container {
            width: 100%;
            margin-top: 0;
            overflow-x: auto;
            overflow-y: auto;
            max-height: 100%;
            background: #fff;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
        }

        .power-table {
            width: 100%;
            border-collapse: collapse;
            background: #fff;
            color: #222;
            table-layout: auto;
        }

        .power-table th,
        .power-table td {
            border: 1px solid #e0e0e0;
            padding: 8px 14px;
            text-align: center;
            min-width: 80px;
            word-break: break-all;
            white-space: pre-line;
        }

        .power-table th {
            position: sticky;
            top: 0;
            background: #f0f0f0;
            color: #ff6600;
            z-index: 1;
            border-bottom: 2px solid #e0e0e0;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
            font-size: 0.98em;
            padding: 6px 8px;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
            max-width: 120px;
        }

        .power-table tr:nth-child(even) {
            background: #f8fafd;
        }

        .status-normal {
            color: #388e3c;
            font-weight: bold;
        }

        .status-level1 {
            color: #ff3b3b;
            font-weight: bold;
        }

        .status-level2 {
            color: #ff6600;
            font-weight: bold;
        }

        .status-level3 {
            color: #e6b800;
            font-weight: bold;
        }

        /* 自定义滚动条样式 */
        .power-table-container::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        .power-table-container::-webkit-scrollbar-track {
            background: #f5f6fa;
            border-radius: 4px;
        }

        .power-table-container::-webkit-scrollbar-thumb {
            background: #e0e0e0;
            border-radius: 4px;
        }

        .power-table-container::-webkit-scrollbar-thumb:hover {
            background: #ccc;
        }

        .param-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #fff;
            border-radius: 8px;
            padding: 14px 28px;
            margin-bottom: 18px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
            font-size: 1.08rem;
            color: #222;
            border: 1px solid #e0e0e0;
            gap: 18px;
        }

        .param-bar>div {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .param-time-range {
            display: flex;
            align-items: center;
            gap: 6px;
            background: #f8fafd;
            border-radius: 6px;
            padding: 4px 12px;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);
            border: 1px solid #e0e0e0;
        }

        .param-time-range input[type="datetime-local"] {
            background: #fff;
            color: #222;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            padding: 2px 6px;
            font-size: 1em;
        }

        .param-time-range input[type="datetime-local"]::-webkit-calendar-picker-indicator {
            filter: invert(0.2);
        }

        .param-search-btn {
            margin-left: 8px;
            padding: 4px 14px;
            background: linear-gradient(90deg, #ff6600, #ff944d);
            border: none;
            border-radius: 4px;
            color: #fff;
            font-size: 1em;
            font-weight: bold;
            cursor: pointer;
            transition: background 0.2s, box-shadow 0.2s;
            box-shadow: 0 2px 8px rgba(255, 102, 0, 0.08);
        }

        .param-search-btn:hover {
            background: linear-gradient(90deg, #ff944d, #ff6600);
            color: #fff;
        }

        .power-table th:nth-child(3), .power-table td:nth-child(3) {
            min-width: 180px;
            max-width: 260px;
            word-break: break-all;
        }

        /* 新增选中行高亮样式 */
        .table-row-selected {
            background: #ffecb3 !important;
            color: #222 !important;
            box-shadow: 0 2px 8px rgba(255, 236, 179, 0.15);
            border-left: 4px solid #ff6600 !important;
        }

        .attenuation-chart-section {
            width: 40% !important;
        }
        .attenuation-list-section {
            width: 60% !important;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="param-bar">
            <div><span>光路</span> <span class="param-highlight" id="param-channel">1</span></div>
            <div><span>工作波长</span> <span class="param-highlight">1550</span> <span
                    style="font-size:0.95em;color:#b0b0b0;">nm</span></div>
            <div><span>光缆长度</span> <span class="param-highlight" id="param-length">80.154</span> <span
                    style="font-size:0.95em;color:#b0b0b0;">km</span></div>
            <div class="param-time-range">
                <span>时间</span>
                <input type="datetime-local" id="startTime">
                <span style="margin:0 6px;">至</span>
                <input type="datetime-local" id="endTime">
                <button class="param-search-btn" onclick="filterByTime()">搜索</button>
            </div>

        </div>
        <div class="chart-tabs">
            <button class="tab-btn active" onclick="showTab('power')">光功率</button>
            <button class="tab-btn" onclick="showTab('attenuation')">损耗</button>
        </div>
        <div class="main-flex">
            <div class="chart-section">
                <div id="powerTab" class="tab-content">
                    <div class="chart-container">
                        <div id="powerChart" class="chart"></div>
                    </div>
                </div>
                <div id="attenuationTab" class="tab-content" style="display:none;">
                    <div class="chart-container">
                        <div id="attenuationChart" class="chart"></div>
                    </div>
                </div>
            </div>
            <div class="list-section attenuation-list-section">
                <div id="powerTableWrap">
                    <div class="power-table-container">
                        <table class="power-table">
                            <thead>
                                <tr>
                                    <th title="序号">序号</th>
                                    <th title="光路">光路</th>
                                    <th title="时间">时间</th>
                                    <th>光功率 (dBm)</th>
                                    <th title="偏差(dB)">偏差(dB)</th>
                                    <th title="告警状态">告警状态</th>
                                </tr>
                            </thead>
                            <tbody id="powerTableBody">
                                <!-- JS动态填充 -->
                            </tbody>
                        </table>
                    </div>
                </div>
                <div id="attenuationTableWrap" style="display:none;">
                    <div class="power-table-container">
                        <table class="power-table">
                            <thead>
                                <tr>
                                    <th title="序号">序号</th>
                                    <th title="光路">光路</th>
                                    <th title="时间">时间</th>
                                    <th title="总损耗(dB)">总损耗(dB)</th>
                                    <th title="平均损耗(dB/km)">平均损耗(dB/km)</th>
                                    <th title="偏差(dB)">偏差(dB)</th>
                                    <th title="告警状态">告警状态</th>
                                </tr>
                            </thead>
                            <tbody id="attenuationTableBody">
                                <!-- JS动态填充 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let outputPowers = [];
        let outputStatus = [];
        // 用户输入参数
        const P_in = -24.98; // 输入端功率 dBm
        const L = 100; // 光纤长度 km
        const normalPower = -25;
        // 生成30组光功率数据
        for (let i = 0; i < 19; i++) {
            let delta = (Math.random() * 0.02 + 0.01) * (Math.random() > 0.5 ? 1 : -1);
            outputPowers.push(Number((normalPower + delta).toFixed(2)));
            outputStatus.push('无告警');
        }
        // 中间5组：异常，变化-0.44*100=-44dB
        for (let i = 0; i < 5; i++) {
            let delta = (Math.random() * 0.02 + 0.01) * (Math.random() > 0.5 ? 1 : -1);
            outputPowers.push(Number((normalPower - 0.44 + delta).toFixed(2)));
            outputStatus.push('无告警');
        }
        // 后6组：-25dBm±0.01~0.03
        for (let i = 0; i < 6; i++) {
            let delta = (Math.random() * 0.02 + 0.01) * (Math.random() > 0.5 ? 1 : -1);
            outputPowers.push(Number((normalPower + delta).toFixed(2)));
            outputStatus.push('无告警');
        }
        // 替换最近6个点为异常值，并同步替换状态
        const abnormalVals = [-33.5, -37.6, -44.3, -45.2, -45.2, -45.3];
        const abnormalStatus = ['二级告警', '二级告警', '一级告警', '一级告警', '一级告警', '一级告警'];
        outputPowers.splice(-6, 6, ...abnormalVals);
        outputStatus.splice(-6, 6, ...abnormalStatus);
        // x轴时间数据，30个点，每个点间隔5分钟，从2024-05-06 12:00:00开始
        const startDate = new Date('2024-05-06T12:00:00');
        const splitDate = new Date('2024-05-06T14:10:00');
        const timeData = Array.from({ length: outputPowers.length }, (_, i) => {
            let d = new Date(startDate.getTime() + i * 5 * 60 * 1000);
            if (d < splitDate) {
                // 早于分界点的点总数
                const earlyCount = outputPowers.length - Array.from({ length: outputPowers.length }, (_, j) => new Date(startDate.getTime() + j * 5 * 60 * 1000)).filter(dt => dt >= splitDate).length;
                // 当前点在早于分界点的倒序索引
                const idx = earlyCount - 1 - i;
                let newDate = new Date(splitDate.getTime() - (idx + 1) * 24 * 60 * 60 * 1000);
                const yyyy = newDate.getFullYear();
                const MM = (newDate.getMonth() + 1).toString().padStart(2, '0');
                const dd = newDate.getDate().toString().padStart(2, '0');
                return `${yyyy}-${MM}-${dd} 14:00:00`;
            } else {
                const yyyy = d.getFullYear();
                const MM = (d.getMonth() + 1).toString().padStart(2, '0');
                const dd = d.getDate().toString().padStart(2, '0');
                const hh = d.getHours().toString().padStart(2, '0');
                const mm = d.getMinutes().toString().padStart(2, '0');
                const ss = d.getSeconds().toString().padStart(2, '0');
                return `${yyyy}-${MM}-${dd} ${hh}:${mm}:${ss}`;
            }
        });
        // 实际光功率曲线
        const powerData = {
            estimated: Array(outputPowers.length).fill(P_in), // 预估为输入端功率
            actual: outputPowers
        };
        // 光功率Y轴自动适应
        const powerMin = Math.floor(Math.min(...outputPowers)) - 2;
        const powerMax = Math.ceil(Math.max(...outputPowers)) + 2;

        // 状态样式映射
        const statusMap = {
            '无告警': '<span class="status-normal">无告警</span>',
            '一级告警': '<span class="status-level1">一级告警</span>',
            '二级告警': '<span class="status-level2">二级告警</span>',
            '三级告警': '<span class="status-level3">三级告警</span>'
        };

        // 美化与交互增强后的ECharts配置
        const powerOption = {
            backgroundColor: '#fff',
            tooltip: {
                trigger: 'axis',
                backgroundColor: '#fff',
                borderColor: '#bdbdbd',
                borderWidth: 1,
                textStyle: { color: '#222', fontWeight: 'bold' },
                axisPointer: { type: 'cross', label: { backgroundColor: '#bdbdbd', color: '#222' } },
                formatter: function (params) {
                    const time = params[0].name;
                    const estimated = params[0].value;
                    const actual = params[1].value;
                    const diff = (actual - estimated).toFixed(2);
                    const status = statusMap[outputStatus[params[1].dataIndex]] || outputStatus[params[1].dataIndex];
                    return `时间: ${time}<br/>基准值: ${estimated} dBm<br/>测量值: ${actual} dBm<br/>差值: ${diff} dB<br/>状态: ${status}`;
                }
            },
            legend: {
                data: [
                    {
                        name: '测量值',
                        icon: 'circle',
                        itemStyle: { color: '#3a7afe' }
                    },
                    {
                        name: '基准值',
                        icon: 'circle',
                        itemStyle: { color: '#bdbdbd' }
                    }
                ],
                textStyle: { color: '#222', fontWeight: 'bold' },
                backgroundColor: '#fff',
                padding: [6, 16],
                top: 10,
                right: 20
            },
            grid: {
                left: '5%',
                right: '5%',
                bottom: '15%',
                top: 60,
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: timeData,
                axisLabel: {
                    color: '#b0b0b0',
                    fontWeight: 'bold',
                    fontSize: 15,
                    interval: 'auto',
                    rotate: 45,
                    formatter: function (value) { return value; }
                },
                axisLine: { lineStyle: { color: '#b0b0b0', width: 2 } }
            },
            yAxis: {
                type: 'value',
                name: '光功率 (dBm)',
                nameTextStyle: { color: '#b0b0b0', fontWeight: 'bold', fontSize: 16 },
                axisLabel: { color: '#b0b0b0', fontWeight: 'bold', fontSize: 15 },
                axisLine: { lineStyle: { color: '#b0b0b0', width: 2 } },
                splitLine: { lineStyle: { color: '#444' } },
                min: powerMin,
                max: powerMax,
                interval: 10
            },
            series: [
                {
                    name: '测量值',
                    type: 'line',
                    data: powerData.actual,
                    smooth: 0.7,
                    symbol: 'none',
                    lineStyle: { width: 4, color: '#3a7afe' },
                    emphasis: {
                        focus: 'series',
                        itemStyle: { borderColor: '#fff', borderWidth: 4 }
                    },
                    label: { show: false }
                },
                {
                    name: '基准值',
                    type: 'line',
                    data: powerData.estimated,
                    smooth: 0.7,
                    symbol: 'none',
                    lineStyle: { width: 3, color: '#bdbdbd', type: 'dashed' },
                    areaStyle: { color: 'rgba(189,189,189,0.04)' },
                    label: { show: false }
                }
            ]
        };
        // 损耗Tab独立数据
        let attenuationTableData = [
            { channel: 2, time: '2024/5/12 13:36:12', totalLoss: 36.45, status: '一级告警' },
            { channel: 2, time: '2024/5/11 13:40:23', totalLoss: 36.36, status: '一级告警' },
            { channel: 2, time: '2024/5/10 13:38:32', totalLoss: 30.57, status: '二级告警' },
            { channel: 2, time: '2024/5/9 13:35:55', totalLoss: 30.16, status: '二级告警' },
            { channel: 2, time: '2024/5/8 13:36:44', totalLoss: 25.52, status: '无告警' },
            { channel: 2, time: '2024/5/7 13:34:56', totalLoss: 25.63, status: '无告警' },
            { channel: 2, time: '2024/5/6 13:30:34', totalLoss: 25.58, status: '无告警' },
            { channel: 2, time: '2024/5/5 13:31:24', totalLoss: 25.65, status: '无告警' }
        ];
        // 对2024-05-05 14:00:00及以前的点做±1~3的随机变化
        const attChangeDate = new Date('2024-05-05T14:00:00');
        const attenuationChartTime = attenuationTableData.map(row => row.time).slice().reverse();
        const attenuationChartTotalLoss = attenuationTableData.map(row => row.totalLoss).slice().reverse();
        const baseTotal = 25.51;
        const fiberLength = 100.154;
        // 损耗图表配置
        const attenuationOption = {
            backgroundColor: '#fff',
            tooltip: {
                trigger: 'axis',
                backgroundColor: '#fff',
                borderColor: '#bdbdbd',
                borderWidth: 1,
                textStyle: { color: '#222', fontWeight: 'bold' },
                axisPointer: { type: 'cross', label: { backgroundColor: '#bdbdbd', color: '#222' } },
                formatter: function (params) {
                    const time = params[0].name;
                    const totalLoss = params[0].value;
                    const dataIndex = params[0].dataIndex;
                    // 关键：倒序索引，保证tooltip和表格一致
                    const row = attenuationTableData[attenuationTableData.length - 1 - dataIndex];
                    const diff = (row.totalLoss - baseTotal).toFixed(3);
                    const avgLoss = (row.totalLoss / fiberLength).toFixed(3);
                    let status = '<span style="color:#4caf50">无告警</span>';
                    if (row.status === '一级告警') status = '<span style="color:#ff4c4c">一级告警</span>';
                    if (row.status === '二级告警') status = '<span style="color:#ffb300">二级告警</span>';
                    if (row.status === '三级告警') status = '<span style="color:#ffe066">三级告警</span>';
                    return `时间: ${time}<br/>基准值: ${baseTotal} dB<br/>总损耗: ${totalLoss} dB<br/>平均损耗: ${avgLoss} dB/km<br/>偏差: ${diff} dB<br/>告警状态: ${status}`;
                }
            },
            legend: {
                data: [
                    {
                        name: '总损耗',
                        icon: 'circle',
                        itemStyle: { color: '#3a7afe' }
                    },
                    {
                        name: '基准值',
                        icon: 'circle',
                        itemStyle: { color: '#bdbdbd' }
                    }
                ],
                textStyle: { color: '#222', fontWeight: 'bold' },
                backgroundColor: '#fff',
                borderRadius: 6,
                padding: [6, 16],
                top: 10,
                right: 20
            },
            grid: {
                left: '5%',
                right: '5%',
                bottom: '15%',
                top: 60,
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: attenuationChartTime,
                axisLabel: {
                    color: '#b0b0b0',
                    fontWeight: 'bold',
                    fontSize: 15,
                    interval: 'auto',
                    rotate: 45,
                    formatter: function (value) { return value; }
                },
                axisLine: { lineStyle: { color: '#b0b0b0', width: 2 } }
            },
            yAxis: {
                type: 'value',
                name: '损耗(dB)',
                nameTextStyle: { color: '#b0b0b0', fontWeight: 'bold', fontSize: 16 },
                axisLabel: { color: '#b0b0b0', fontWeight: 'bold', fontSize: 15 },
                axisLine: { lineStyle: { color: '#b0b0b0', width: 2 } },
                splitLine: { lineStyle: { color: '#444' } },
                min: 0,
                max: 50,
            },
            series: [
                {
                    name: '总损耗',
                    type: 'line',
                    data: attenuationChartTotalLoss,
                    smooth: 0.7,
                    symbol: 'none',
                    lineStyle: { width: 4, color: '#3a7afe' },
                    emphasis: {
                        focus: 'series',
                        itemStyle: { borderColor: '#fff', borderWidth: 4 }
                    },
                    label: { show: false }
                },
                {
                    name: '基准值',
                    type: 'line',
                    data: Array(attenuationChartTime.length).fill(baseTotal),
                    smooth: false,
                    symbol: 'none',
                    lineStyle: { width: 3, color: '#bdbdbd', type: 'dashed' },
                    label: { show: false }
                }
            ]
        };
        // 应用配置
        const powerChart = echarts.init(document.getElementById('powerChart'));
        const attenuationChart = echarts.init(document.getElementById('attenuationChart'));
        powerChart.setOption(powerOption);
        attenuationChart.setOption(attenuationOption);
        window.addEventListener('resize', function () {
            powerChart.resize();
            attenuationChart.resize();
        });
        function exportChart(chartId) {
            const chart = echarts.getInstanceByDom(document.getElementById(chartId));
            const url = chart.getDataURL({
                type: 'png',
                pixelRatio: 2,
                backgroundColor: '#203a43'
            });
            const a = document.createElement('a');
            a.href = url;
            a.download = chartId + '.png';
            a.click();
        }
        function showTab(tab) {
            document.getElementById('powerTab').style.display = tab === 'power' ? '' : 'none';
            document.getElementById('attenuationTab').style.display = tab === 'attenuation' ? '' : 'none';
            document.getElementById('powerTableWrap').style.display = tab === 'power' ? '' : 'none';
            document.getElementById('attenuationTableWrap').style.display = tab === 'attenuation' ? '' : 'none';
            document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelector('.tab-btn[onclick*="' + tab + '"]').classList.add('active');
            if (tab === 'power' && window.powerChart) {
                powerChart.resize();
            }
            if (tab === 'attenuation' && window.attenuationChart) {
                attenuationChart.resize();
            }
            updateParamBar(tab);
        }
        function filterByTime() {
            const start = document.getElementById('startTime').value;
            const end = document.getElementById('endTime').value;
            // 光功率表格
            let filteredPowerIdx = [];
            for (let i = 0; i < timeData.length; i++) {
                const t = timeData[i].replace(/-/g, '/');
                if ((!start || new Date(t) >= new Date(start)) && (!end || new Date(t) <= new Date(end))) {
                    filteredPowerIdx.push(i);
                }
            }
            renderPowerTable(filteredPowerIdx);
            // 损耗表格
            let filteredAttIdx = [];
            for (let i = 0; i < attenuationTableData.length; i++) {
                const t = attenuationTableData[i].time.replace(/-/g, '/');
                if ((!start || new Date(t) >= new Date(start)) && (!end || new Date(t) <= new Date(end))) {
                    filteredAttIdx.push(i);
                }
            }
            renderAttenuationTable(filteredAttIdx);
        }
        function renderPowerTable(filteredIdx) {
            const tbody = document.getElementById('powerTableBody');
            if (!tbody) return;
            tbody.innerHTML = '';
            const channel = 1;
            let rowNum = 1;
            let idxArr = filteredIdx || Array.from({length: outputPowers.length}, (_, i) => i);
            for (let k = idxArr.length - 1; k >= 0; k--) { // 倒序，最新在上
                const i = idxArr[k];
                const diff = (outputPowers[i] - P_in).toFixed(2);
                const status = statusMap[outputStatus[i]] || outputStatus[i];
                tbody.innerHTML += `
                  <tr id="power-row-${i}" onclick="selectTableRowAndShowTooltip(${i}, 'power')" style="cursor:pointer;">
                    <td>${rowNum++}</td>
                    <td>${channel}</td>
                    <td>${timeData[i]}</td>
                    <td>${outputPowers[i]}</td>
                    <td>${diff}</td>
                    <td>${status}</td>
                  </tr>
                `;
            }
        }
        function showChartTooltip(dataIndex) {
            showTab('power');
            powerChart.dispatchAction({
                type: 'showTip',
                seriesIndex: 1,
                dataIndex: dataIndex
            });
            powerChart.dispatchAction({
                type: 'highlight',
                seriesIndex: 1,
                dataIndex: dataIndex
            });
            setTimeout(() => {
                powerChart.dispatchAction({
                    type: 'downplay',
                    seriesIndex: 1
                });
            }, 2000);
        }
        powerChart.on('showTip', function () {
            clearTableRowSelected();
        });
        function renderAttenuationTable(filteredIdx) {
            const tbody = document.getElementById('attenuationTableBody');
            if (!tbody) return;
            tbody.innerHTML = '';
            let idxArr = filteredIdx || Array.from({length: attenuationTableData.length}, (_, i) => i);
            for (let k = 0; k < idxArr.length; k++) {
                const i = idxArr[k];
                const row = attenuationTableData[i];
                const avgLoss = (row.totalLoss / fiberLength).toFixed(4);
                const diff = (row.totalLoss - baseTotal).toFixed(2);
                let statusHtml = '<span class="status-normal">无告警</span>';
                if (row.status === '一级告警') statusHtml = '<span class="status-level1">一级告警</span>';
                if (row.status === '二级告警') statusHtml = '<span class="status-level2">二级告警</span>';
                if (row.status === '三级告警') statusHtml = '<span class="status-level3">三级告警</span>';
                tbody.innerHTML += `
                  <tr id="att-row-${i}" onclick="selectTableRowAndShowTooltip(${i}, 'attenuation')" style="cursor:pointer;">
                    <td>${k + 1}</td>
                    <td>${row.channel}</td>
                    <td>${row.time}</td>
                    <td>${row.totalLoss}</td>
                    <td>${avgLoss}</td>
                    <td>${diff}</td>
                    <td>${statusHtml}</td>
                  </tr>
                `;
            }
        }
        function showAttenuationTooltip(dataIndex) {
            showTab('attenuation');
            const chartIndex = attenuationTableData.length - 1 - dataIndex;
            attenuationChart.dispatchAction({
                type: 'showTip',
                seriesIndex: 0,
                dataIndex: chartIndex
            });
            attenuationChart.dispatchAction({
                type: 'highlight',
                seriesIndex: 0,
                dataIndex: chartIndex
            });
            setTimeout(() => {
                attenuationChart.dispatchAction({
                    type: 'downplay',
                    seriesIndex: 0
                });
            }, 2000);
        }
        attenuationChart.on('showTip', function () {
            clearTableRowSelected();
        });
        // 新增参数栏动态切换函数
        function updateParamBar(tab) {
            if (tab === 'power') {
                document.getElementById('param-channel').innerText = '1';
                document.getElementById('param-length').innerText = '80.154';
                document.getElementById('startTime').value = '2024-04-10T14:00:00';
                document.getElementById('endTime').value = '2024-05-06T14:35:00';
            } else {
                document.getElementById('param-channel').innerText = '2';
                document.getElementById('param-length').innerText = '100.154';
                document.getElementById('startTime').value = '2024-05-05T12:00:00';
                document.getElementById('endTime').value = '2024-05-12T14:00:00';
            }
        }
        // 页面初始时设置参数栏为光功率Tab
        updateParamBar('power');
        // 页面加载时渲染两个表格
        renderPowerTable();
        renderAttenuationTable();

        // JS部分
        function selectTableRowAndShowTooltip(index, type) {
            // 先移除所有选中
            document.querySelectorAll('.power-table tbody tr').forEach(tr => tr.classList.remove('table-row-selected'));
            // 当前行加高亮
            let rowId = type === 'power' ? 'power-row-' + index : 'att-row-' + index;
            let tr = document.getElementById(rowId);
            if (tr) tr.classList.add('table-row-selected');
            // 显示tooltip
            if (type === 'power') {
                showChartTooltip(index);
            } else {
                showAttenuationTooltip(index);
            }
        }
        // 新增清除表格选中高亮函数
        function clearTableRowSelected() {
            document.querySelectorAll('.power-table tbody tr').forEach(tr => tr.classList.remove('table-row-selected'));
        }
    </script>
</body>

</html>